<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '修改采购申请' : '新建采购申请'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: true,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的采购申请${entity.caseid}`, variables: { days: entity.days } }),
      submit: submitAudit,
      finish: () => submitAudit({ isFinish: true, entity }),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <FormHolder ref="form" label-width="100px" :model="entity" :disabled="entity.status === '2'">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.caseid" prop="caseid" label="申请单号" disabled />
        <FormSelect v-model="entity.type" label="单据类型" dict-type="type_document" classic prop="type" required />
        <FormTreeSelect
          v-model="entity.purchaseOuid"
          :span="24"
          label="采购单位"
          :options="dictData.deptTreeList"
          prop="purchaseOuid"
          required />
        <FormInput
          v-model="entity.budgetNumber"
          prop="budgetNumber"
          legacy
          value-prop="id"
          label-prop="name"
          placeholder="请选择所属预算`"
          label="预算"
          @clear="clearBedget">
          <template #append>
            <ElButton type="button" style="padding-right: 10px" @click="isShowBudgetShow = true">选择</ElButton>
          </template>
        </FormInput>
        <FormSelect
          v-model="entity.supplierId"
          :options="dictData.supplierTreeList"
          prop="supplierId"
          legacy
          value-prop="id"
          filterable
          label-prop="name"
          label="供应商" />
        <FormDatePicker v-model="entity.arrivalDatetime" date-time label="期望到货时间" prop="arrivalDatetime" />
        <FormSelect
          v-model="entity.method"
          label="采购方式"
          :options="dictData.purchaseWayList"
          prop="purchaseWayList" />
        <FormInputNumber v-model="entity.amount" label="购置价格" prop="amount" disabled />
        <FormSelect
          v-model="entity.currencyType"
          dict-type="currency_type"
          classic
          label="货币类型"
          prop="currencyType"
          required />
        <FormInput v-model="entity.receivinfo" :span="24" label="收货信息" prop="receivinfo" max-length="255" />
        <FormTextarea v-model="entity.explains" rows="5" label="申请说明" prop="explains" max-length="3000" />
        <ElCol :span="24">
          <FlexRow vertical-center style="padding: 10px">
            <FlexItem><span style="color: #f56c6c">*</span>申请明细-物品列表</FlexItem>
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="tableVisible = true">
              从其它申请单复制</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="isPickerShow = true">
              添加</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-delete" @click="deleteSelectCard"> 删除所选</ElButton>
          </FlexRow>
          <FormTable
            ref="formTable"
            v-model="entity.purchaseapplyList"
            prop="purchaseapplyList"
            required
            selection-width="60"
            placeholder="请选择物品"
            editable
            :show-summary="true"
            hide-label
            :handle-column="false"
            :columns="[
              { label: '名称', prop: 'name' },
              { label: '规格型号', prop: 'model' },
              { label: '计量单位', prop: 'unit' },
              { label: '单价', prop: 'price' },
              { label: '申请数量', prop: 'quantity', required: true, type: 'number' },
              { label: '预计费用', prop: 'amount', type: 'number' },
              { label: '备注', prop: 'remarks', type: 'input' }
            ]" />
        </ElCol>
      </FormItemGroup>
      <FormItemGroup :gutter="0" block-title="附件信息">
        <UploadPage
          v-if="entity.unid"
          ref="UploadPage"
          style="padding: 0"
          :unique-code="entity.unid"
          model="purchaseOrder"
          classify="purchaseOrder" />
      </FormItemGroup>
    </FormHolder>
    <!-- 流程发送选择框 -->
    <FlowableHandleUserTable :visible.sync="visibleUser" :selection="true" :multiple="true" />
    <AssetSauTable
      :visible.sync="isPickerShow"
      :asset-card-id="entity.id"
      :in-type="entity.type"
      :multiple="true"
      @confirm="onConfirm" />
    <SelectApplyListTable :visible.sync="tableVisible" @confirm="onApplyList" />
    <SelectBudgetTable :visible.sync="isShowBudgetShow" @confirm="onBudgetList" />
  </FormView>
</template>

<script>
  import { addObj, edit, putObj, create } from '@/api/asset/fyassetpurchaseapply'

  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable'
  import flowForm from '@/vue/mixin/flow-form'
  import { delApplyListObj } from '@/api/asset/fyassetpurchaseapplylist'

  export default {
    name: 'PurchaseApplyForm',
    docType: 'PurchaseApply',
    relativeViewId: 'PurchaseApplyView',
    components: {
      FlowableHandleUserTable
    },
    mixins: [flowForm],
    data() {
      return {
        selectedRows: [],
        isPickerShow: false,
        tableVisible: false,
        isShowBudgetShow: false,
        entity: {
          rows: '',
          amount: null,
          arrivalDatetime: null,
          batchnumber: null,
          budgetId: null,
          budgetName: null,
          budgetNumber: null,
          caseid: null,
          createBy: 'liyue',
          createId: 3,
          createTime: '2021-12-13 16:08:39',
          currencyType: '人民币',
          delFlag: null,
          deptFullname: '山东',
          deptId: 1,
          detailed: '',
          dictOption: {
            budgetTreeList: [],
            currencyTypeList: [],
            deptTreeList: [],
            purchaseWayList: [],
            supplierTreeList: [],
            typeList: []
          },
          explains: null,
          id: '',
          method: null,
          purchaseOufullname: null,
          purchaseOuid: null,
          purchaseOuname: null,
          receivinfo: null,
          status: '0',
          supplierId: null,
          supplierName: null,
          type: 'ALL',
          unid: '',
          updateBy: null,
          updateTime: null,
          purchaseapplyList: [],
          processInstanceId: ''
        },
        visibleUser: false
      }
    },
    methods: {
      create,
      load: edit,
      save: addObj,
      update: putObj,
      onApplyList(rows) {
        this.handlePurchaseapplyList(rows)
        const row = rows[0]
        this.entity.type = row.type
        this.entity.budgetId = row.budgetId
        this.entity.budgetNumber = row.budgetNumber
        this.entity.supplierId = row.supplierId
        this.entity.supplierName = row.supplierName
        this.entity.receivinfo = row.receivinfo
        this.entity.method = row.method
        this.entity.currencyType = row.currencyType
        this.entity.purchaseapplyList = rows
      },
      onConfirm(rows) {
        this.handlePurchaseapplyList(rows)
        const row = rows[0]
        this.entity.type = row.ctiType
      },
      onBudgetList(budget) {
        this.entity.budgetId = budget.id
        this.entity.budgetNumber = budget.number
        this.entity.budgetName = budget.type
      },
      handlePurchaseapplyList(rows) {
        if (!this.entity.purchaseapplyList?.length) {
          rows.forEach(value => {
            this.$set(value, 'id', null)
            this.$set(value, 'quantity', 1 || undefined)
            this.$set(value, 'price', value.amount || undefined)
          })
          this.entity.purchaseapplyList = rows
        } else {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            this.$set(row, 'quantity', 1 || undefined)
            this.$set(row, 'price', row.amount || undefined)
            if (!this.entity.purchaseapplyList.find(value => value.sauId === row.sauId)) {
              this.entity.purchaseapplyList.push(row)
            }
          })
        }
      },
      deleteSelectCard() {
        this.selectedRows = this.$refs.formTable.selectedRows
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要删除的物品列表')
          return
        }
        const deleteIds = this.selectedRows.filter(item => item.id > 0).map(item => item.id)
        this.$confirm(`是否确认删除"${this.selectedRows.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delApplyListObj(deleteIds)
            }
            this.entity.purchaseapplyList = this.entity.purchaseapplyList.filter(
              value => !this.selectedRows.includes(value)
            )
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      clearBedget() {
        this.entity.budgetId = ''
        this.entity.budgetNumber = ''
        this.entity.budgetName = ''
      }
    }
  }
</script>
